var app = getApp()
var util = require('../../utils/util.js')
var Bmob = require('../../utils/bmob.js');
Page({
  data: {
    couponList: [],
    receiveSuccess: 0,  // 领取成功弹窗是否显示
    receiveCount: 0,    // 已领取数量
    receiveLimitNum: 0, // 领取限制数量
    mycoupon: ''
  },
  onLoad: function (e) {
    let _this = this;
    console.log(e);
    var franchiseeId = e.franchiseeId;
    _this.getcouponList(franchiseeId);
    /*
     app.sendRequest({
       url: '/index.php?r=AppShop/getCoupons',
       data: {
         app_id: app.getAppId(),
         in_show_list: 1,  //0:不在列表内 1:在列表内
         enable_status: 1, //0:下架 1:上架
         stock: 1,         //0:没有库存的 1:有库存的
         page: -1
       },
       hideLoading: true,
       success: function(res) {
         _this.setData({
           couponList: res.data
         });
       }
     })*/
  },
  getcouponList: function (franchiseeId) {
    let _this = this;
    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Franchisee();
    franchisee.id = franchiseeId;
    var CouponList = Bmob.Object.extend("coupon");
    var couponList = new Bmob.Query(CouponList);
    couponList.equalTo("franchiseeID", franchisee);
    couponList.notEqualTo("stock", 0);
    couponList.equalTo("enable_status", 1);
    //排序

    couponList.find({
      success: function (res) {
        //var goods=res;
        _this.setData({
          couponList: res
        })
      },
      complete: function () {

      }
    });

  },

  // 跳转优惠券详情(领取状态)
  gotoCouponDetail: function (event) {
    let url = '/pages/couponDetail/couponDetail?detail=' + event.currentTarget.dataset.couponId;
    app.turnToPage(url, false);
  },
  // 领取优惠券
  receiveCoupon: function (event) {
    let _this = this;
    console.log(event)
    let couponId = event.currentTarget.dataset.couponId;
    var index = event.currentTarget.dataset.index;

    var currentUser = Bmob.User.current();
    var objectId = currentUser.id;
    var isme = new Bmob.User();
    isme.id = objectId;

    var CouponList = Bmob.Object.extend("coupon");
    var couponList = new CouponList();
    couponList.id = couponId;

    var myCoupon = Bmob.Object.extend("mycoupon");
    var mycoupon = new Bmob.Query(myCoupon);
    mycoupon.equalTo("couponInfo", couponList)
    mycoupon.equalTo("userInfo", isme);
    mycoupon.find({
      success: function (res) {
        //var goods=res;
console.log(res);
        if (res.length > 0) {
          if (res[0].get("rev_stock") < _this.data.couponList[index].get("limit_stock")){
            
            res[0].set("rev_stock", res[0].get("rev_stock")+1);
            res[0].set("status", 1);
            res[0].set("limit_stock", _this.data.couponList[index].get("limit_stock"));
            res[0].save(null,{
              success: function () {
               
                _this.setData({
                  
                  receiveSuccess: 1,
                  receiveCount: res[0].get("rev_stock"),
                  receiveLimitNum: _this.data.couponList[index].get("limit_stock")
                })}

            });
           
}
          else {
                     
            _this.setData({
              ['couponList[' + index + '].recv_status']: 0,
              receiveSuccess: 1,
              receiveCount: res[0].get("rev_stock"),
              receiveLimitNum: _this.data.couponList[index].get("limit_stock")
            })
          }}
          if (res.length == 0) {
            console.log(res.length)
            var myCoupon = Bmob.Object.extend("mycoupon");
            var mycoupon = new myCoupon();
            mycoupon.set("userInfo", isme);
            mycoupon.set("couponInfo", couponList);
            mycoupon.set("rev_stock", 1);
            mycoupon.set("status", 1);
            mycoupon.set("limit_stock", _this.data.couponList[index].get("limit_stock"));
            mycoupon.save(null, {
              success: function (res) {
                // 添加成功，返回成功之后的objectId（注意：返回的属性名字是id，不是objectId），你还可以在Bmob的Web管理后台看到对应的数据
                console.log(res);
                _this.setData({
                  receiveSuccess: 1,
                  receiveCount: res.rev_stock+1,
                  receiveLimitNum: _this.data.couponList[index].get("limit_stock")
                });
                setTimeout(function () {
                  _this.hideToast();
                }, 3000);

              },
              error: function (result, error) {
                // 添加失败
                console.log('创建日记失败');

              }
            });
          }

        
      },
      complete: function () {

      }
    });

  },
  // 查看我的优惠券
  gotoCouponList: function () {
    let url = '/pages/couponList/couponList';
    app.turnToPage(url, false);
  },
  // 关闭toast
  hideToast: function () {
    this.setData({
      receiveSuccess: 0,
      receiveCount: 0,
      receiveLimitNum: 0
    });
  }
})
